import 'package:flutter/material.dart';
import '../services/script_runner_service.dart';
import 'dart:io';

class ScriptRunnerViewModel extends ChangeNotifier {
  late ScriptRunnerService _service;

  // 项目设置
  String outputPath = "";
  String projectName = "hzy_example_project";
  String packageName = "com.example.hzy_example_project";
  String displayName = "Hzy Example Project";
  String projectType = "app";
  String templateType = "1";
  String ideChoice = "vscode";
  String flutterSdkPath = "请选择";

  // 命令输出
  String commandOutput = "";

  // 运行状态
  bool isRunning = false;

  ScriptRunnerViewModel() {
    init();
  }

  void init() {
    // 创建服务并设置回调
    _service = ScriptRunnerService(
      onOutputUpdated: _handleOutputUpdated,
      onRunningStateChanged: _handleRunningStateChanged,
    );

    // 初始化输出路径为桌面
    _initOutputPath();
  }

  // 初始化输出路径
  Future<void> _initOutputPath() async {
    outputPath = await _service.getDesktopPath();
    notifyListeners();
  }

  // 处理输出更新
  void _handleOutputUpdated(String output) {
    commandOutput += output;
    notifyListeners();
  }

  // 处理运行状态变化
  void _handleRunningStateChanged(bool running) {
    isRunning = running;
    notifyListeners();
  }

  // 更新输出路径
  void updateOutputPath(String path) {
    outputPath = path;
    notifyListeners();
  }

  // 更新项目名称
  void updateProjectName(String name) {
    projectName = name;
    notifyListeners();
  }

  // 更新包名
  void updatePackageName(String name) {
    packageName = name;
    notifyListeners();
  }

  // 更新显示名称
  void updateDisplayName(String name) {
    displayName = name;
    notifyListeners();
  }

  // 更新项目类型
  void updateProjectType(String type) {
    projectType = type;
    notifyListeners();
  }

  // 更新模板类型
  void updateTemplateType(String type) {
    templateType = type;
    notifyListeners();
  }

  // 更新IDE选择
  void updateIdeChoice(String choice) {
    ideChoice = choice;
    notifyListeners();
  }

  // 更新Flutter SDK路径
  void updateFlutterSdkPath(String path) {
    flutterSdkPath = path;
    notifyListeners();
  }

  // 在运行脚本前验证并修复Flutter权限
  Future<bool> _prepareFlutterPermissions() async {
    _handleOutputUpdated("\n=== 准备Flutter环境 ===\n");

    // 首先尝试修复指定路径的权限
    if (flutterSdkPath.isNotEmpty && flutterSdkPath != "请选择") {
      _handleOutputUpdated("\n验证用户指定的Flutter SDK: $flutterSdkPath\n");
      final file = File(flutterSdkPath);

      if (await file.exists()) {
        await _service.fixFlutterPermissions(flutterSdkPath);
      } else {
        _handleOutputUpdated("\n警告: 指定的Flutter SDK路径不存在\n");
      }
    }

    // 尝试备用策略 - 查找系统Flutter
    try {
      final result = await Process.run('which', ['flutter']);
      if (result.exitCode == 0 && result.stdout.toString().trim().isNotEmpty) {
        final systemPath = result.stdout.toString().trim();
        _handleOutputUpdated("\n找到系统Flutter: $systemPath\n");

        // 如果我们没有指定路径或指定路径不存在，使用系统路径
        if (flutterSdkPath.isEmpty ||
            flutterSdkPath == "请选择" ||
            !(await File(flutterSdkPath).exists())) {
          flutterSdkPath = systemPath;
          notifyListeners();
          _handleOutputUpdated("\n自动填充Flutter SDK路径为系统路径\n");
        }

        // 修复系统Flutter权限
        await _service.fixFlutterPermissions(systemPath);
      }
    } catch (e) {
      _handleOutputUpdated("\n定位系统Flutter时出错: $e\n");
    }

    // 最后的备用方案，在常见位置搜索Flutter
    if (flutterSdkPath.isEmpty ||
        flutterSdkPath == "请选择" ||
        !(await File(flutterSdkPath).exists())) {
      _handleOutputUpdated("\n在常见位置搜索Flutter...\n");
      final foundPath = await _service.findAndFixFlutter();
      if (foundPath.isNotEmpty) {
        flutterSdkPath = foundPath;
        notifyListeners();
        _handleOutputUpdated("\n找到并修复了Flutter: $foundPath\n");
        return true;
      } else {
        _handleOutputUpdated("\n找不到有效的Flutter安装\n");
        return false;
      }
    }

    return true;
  }

  // 验证脚本参数是否有效
  Future<String?> validateScriptParams() async {
    // 校验项目名称
    if (projectName.isEmpty) {
      return "项目名称不能为空";
    }
    if (!RegExp(r'^[a-z0-9_]+$').hasMatch(projectName)) {
      return "项目名称只能包含小写字母、数字和下划线";
    }

    // 校验包名
    if (packageName.isEmpty) {
      return "包名不能为空";
    }
    if (!RegExp(r'^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$').hasMatch(packageName)) {
      return "包名格式不正确，应为有效的域名格式，如：com.example.app";
    }

    // 校验显示名称
    if (displayName.isEmpty) {
      return "显示名称不能为空";
    }

    // 校验输出路径
    if (outputPath.isEmpty) {
      return "输出目录不能为空";
    }

    // 安全检查输出目录是否存在
    try {
      final Directory outputDir = Directory(outputPath);
      bool exists = await outputDir.exists();
      if (!exists) {
        return "输出目录不存在：$outputPath";
      }

      // 检查是否有写入权限
      try {
        final testFile = File('$outputPath/.flutter_test_write');
        await testFile.writeAsString('test');
        await testFile.delete();
      } catch (e) {
        return "无法写入输出目录，请检查权限: $outputPath";
      }
    } catch (e) {
      return "检查输出目录时出错: $e";
    }

    // 校验Flutter SDK路径
    if (flutterSdkPath == "请选择") {
      return "请选择Flutter SDK路径";
    }

    if (flutterSdkPath != "flutter") {
      // 如果不是系统默认的flutter命令
      try {
        final flutterFile = File(flutterSdkPath);
        if (!await flutterFile.exists()) {
          return "Flutter SDK路径不存在: $flutterSdkPath";
        }
      } catch (e) {
        return "检查Flutter SDK路径时出错: $e";
      }
    }

    // 所有参数有效
    return null;
  }

  // 运行脚本
  Future<bool> runScript() async {
    // 检查所有参数是否有效
    final String? validationError = await validateScriptParams();
    if (validationError != null) {
      commandOutput = "错误: $validationError\n请修正参数后再试。\n";
      notifyListeners();
      return false;
    }

    commandOutput = "准备运行脚本...\n";
    notifyListeners();

    // 首先检查并修复Flutter权限
    await _prepareFlutterPermissions();

    return _service.runScript(
      projectType: projectType,
      templateType: templateType,
      projectName: projectName,
      packageName: packageName,
      displayName: displayName,
      outputPath: outputPath,
      ideChoice: ideChoice,
      flutterSdkPath: flutterSdkPath,
    );
  }

  // 停止脚本
  void stopScript() {
    _service.stopScript();
  }

  // 清理资源
  @override
  void dispose() {
    _service.dispose();
    super.dispose();
  }
}
